package com.qiu.demo.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.qiu.demo.enums.HttpCodeEnum;

import cn.hutool.core.lang.UUID;

@Component
public class UploadFileUtils {

    private final  String URL = "http://localhost:8080/";

    @Value("${file.path}")
    private  String filePath;

    public  String upload(MultipartFile file) {
        // 获取项目classes/static的地址
        String path = filePath;
        // String fileName = file.getOriginalFilename(); // 获取文件名
        String fileOrigrec = file.getOriginalFilename();
        String ext = fileOrigrec.substring(fileOrigrec.lastIndexOf('.'));
        String fileName = UUID.randomUUID().toString() + ext; // 获取文件名
        // 图片访问URI(即除了协议、地址和端口号的URL)
        String url_path = "image" + File.separator + fileName;
        String savePath = path + File.separator + url_path; // 图片保存路径
        File saveFile = new File(savePath);

        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }
        try {
            file.transferTo(saveFile); // 将临时存储的文件移动到真实存储路径下
            return URL + url_path;
        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }
    }

    public  String getFileNameByFilePath(String filePath) {
        String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
        return fileName;
    }

    public  Integer checkFileType(String fileName){
        String[] imageExtensions = {"jpg", "jpeg", "png", "gif", "bmp", "webp"};
        for (String ext : imageExtensions) {
            if (fileName.contains(ext)) {
                return 1;
            }
        }
        String[] videoExtensions = {"mp4", "avi", "mov", "mkv", "flv", "wmv"};
        for (String ext : videoExtensions) {
            if (fileName.contains(ext)) {
                return -1;
            }
        }
        return 0;
    }

}
